//	capsule.h : Simple ping capsule main file.
//
//#pragma warning(disable:4101) // warning C4101: unreferenced local variable

#include <Windows.h>
#include "GradeIface.h"
#include "gkadpingiface.h"

#include <iostream>
#include <fstream>
#include <string>

#include <stdio.h>

using namespace gKad;

//	Simple ping capsule. Compares whether it is in destination node. If so, it
//	turns its way back.
void __stdcall EvalNode(ICapsuleAPI *capsule_api) {
	IServer		*server;
	IStream		*stream;
	TGradeAddr	localAddr;
	struct s_ping	capsuleData;
	LARGE_INTEGER	start;
	ULARGE_INTEGER	tmp;

	capsule_api->GetServer(&server);
	capsule_api->GetDataLoad(&stream);

	// get local addres
	server->Address(&localAddr);
	
	start.HighPart = 0;
	start.LowPart = 0;
	stream->Seek(start, STREAM_SEEK_SET, &tmp);
	stream->Read(&capsuleData, sizeof(struct s_ping), NULL);

/////////////////////////////
/////////////////////////////
	if (IsEqualGUID(localAddr, capsuleData.dstAddr)) {	// dest node
#ifdef _DEBUG
		ILogger		*logger;
		capsule_api->GetLogger(&logger);
		logger->LogString("PING: destination reached");
#endif
		
		capsuleData.alive = true;
		capsule_api->SetDst(capsuleData.srcAddr);

		stream->Seek(start, STREAM_SEEK_SET, &tmp);
		stream->Write(&capsuleData, sizeof(capsuleData), NULL);
/////////////////////////////
/////////////////////////////
	} else if (IsEqualGUID(localAddr, capsuleData.srcAddr)) {	// src node
#ifdef _DEBUG
		ILogger		*logger;
		capsule_api->GetLogger(&logger);
		logger->LogString("PING: back at home");
#endif

		stream->Seek(start, STREAM_SEEK_SET, &tmp);
		int ret = capsule_api->SendData(capsuleData.srcApp, stream);
		if (ret != 0) {
			logger->LogString("Error reading data from capsule.");
		}

		capsule_api->Finish();	// end the capsules life
	}
}
